package cn.cloudplug.core.net.callback;

import android.support.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Watt on 2017/12/20.
 */

public class RequestCallbacks implements Callback<String> {

    private final IRequest request;
    private final ISuccess success;
    private final IFailure failure;
    private final IError error;

    public RequestCallbacks(IRequest request, ISuccess success, IFailure failure, IError error) {
        this.request = request;
        this.success = success;
        this.failure = failure;
        this.error = error;
    }

    @Override
    public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
        if(response.isSuccessful()) {
            if (call.isExecuted())
                if (success != null) {
                    JSONObject object;
                    try {
                        object = JSON.parseObject(response.body());
                    }catch (JSONException e){
                       error.onError(-1, "网络错误");
                       return;
                    }
                    int code = Integer.valueOf(object.getString("code"));
                    if(code!=0){
                        error.onError(code, object.getString("msg"));
                    }
                    success.onSuccess(object.getString("data"));
                }
        }else if(error!=null)
            error.onError(response.code(), response.message());
        onRequestEnd();
    }

    @Override
    public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
        if(failure!=null)
            failure.onFailure(call,t);
        onRequestEnd();
    }
    private void onRequestEnd(){
        if(request!=null)
            request.onEnd();
    }
}
